<template>
  <div class="container">
    <div class="app-container">
      <template>
        <div class="container">
          <div class="app-container">
            <!-- 角色管理内容 -->
            <div class="role-operate">
              <el-button
                v-permission="'add-role'"
                size="mini"
                type="primary"
                @click="dialogVisible = true"
              >添加角色</el-button>
            </div>

            <!-- 放置table组件 -->
            <el-table :data="roleData">
              <!-- 放置列 -->
              <el-table-column align="center" width="200" label="序号" prop="id" />
              <el-table-column align="center" width="200" label="角色" prop="name">
                <template #default="{ row }">
                  <el-input v-if="row.isEdit" v-model="row.editTemp.name" size="mini" />
                  <span v-else>{{ row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" width="200" label="启用">
                <!-- <template slot-scope="scope"> -->
                <!-- v-slot就是找默认插槽 -->
                <template #default="{ row }">
                  <el-switch
                    v-if="row.isEdit"
                    v-model="row.editTemp.state"
                    change="handleChange"
                    :active-value="1"
                    :inactive-value="0"
                  />
                  <span v-else> {{ row.state === 1 ? "已启用" : "未启用" }}</span>

                </template>
              </el-table-column>
              <el-table-column align="center" label="描述">
                <template #default="{ row }">
                  <el-input v-if="row.isEdit" v-model="row.editTemp.description" size="mini" type="textarea" />
                  <span v-else>{{ row.description }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template #default="{ row }">
                  <template v-if="row.isEdit">
                    <el-button size="mini" type="primary" @click="onEditConfirm(row)">确定</el-button>
                    <el-button size="mini" @click="row.isEdit = false">取消</el-button>
                  </template>
                  <template v-else>
                    <el-button
                      v-permission="'assign-role'"
                      size="mini"
                      type="text"
                      @click="btnPermission(row.id)"
                    >分配权限</el-button>
                    <el-button v-permission="'edit-role'" size="mini" type="text" @click="openEdit(row)">编辑</el-button>
                    <el-popconfirm title="确定要删除该用户吗？" style="margin-left:10px" @onConfirm="delRole(row.id)">
                      <el-button slot="reference" v-permission="'del-role'" size="mini" type="text">删除</el-button>
                    </el-popconfirm>
                  </template>
                </template>
              </el-table-column>
            </el-table>

            <!-- 放置分页组件 -->
            <el-row type="flex" style="height: 60px" align="middle" justify="center">
              <!-- 放置分页组件 -->
              <el-pagination
                :current-page="params.page"
                :page-size="params.pagesize"
                layout="total, prev, pager, next"
                :total="total"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </div>
        </div>
      </template>
    </div>
    <add-role :dialog-visible.sync="dialogVisible" @updateRoleList="handleCurrentChange" />
    <!-- 分配权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <el-tree
        ref="perTreeRef"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        :default-checked-keys="permIds"
        default-expand-all
        show-checkbox
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { assignPermApi, delRoleApi, getRoleDetailApi, getRoleListApi, updateRoleApi } from '@/api/role'
import AddRole from './components/add-role.vue'
import { transListToTreeData } from '@/utils'
import { getPermissionListApi } from '@/api/permission'

export default {
  name: 'Role',
  components: {
    AddRole
  },
  data() {
    return {
      dialogVisible: false,
      roleData: [],
      params: {
        page: 1,
        pagesize: 5
      },
      total: 0,
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.handleCurrentChange()
  },
  methods: {
    async handleCurrentChange(page) {
      console.log(this.params.page)
      if (!page) {
        page = this.params.page
      }
      this.params.page = page

      const res = await getRoleListApi(this.params)
      this.total = res.total
      this.roleData = res.rows
      this.roleData.forEach(element => {
        this.$set(element, 'isEdit', false)
        this.$set(element, 'editTemp', {
          name: element.name,
          description: element.description,
          state: element.state
        })
      })
    },
    openEdit(row) {
      row.isEdit = true
      row.editTemp.description = row.description
      row.editTemp.state = row.state
      row.editTemp.name = row.name
    },
    async onEditConfirm(row) {
      // 1、校验数据
      if (!row.editTemp.name.trim() || !row.editTemp.description.trim()) {
        this.$message.warning('用户名称或描述不能为空~')
        return
      }
      // 2、调接口
      await updateRoleApi({ id: row.id, ...row.editTemp })
      this.$message.success('更新用户成功~')
      // 3、退出编辑
      Object.assign(row, {
        // 自带不用拷
        // id: row.id,
        isEdit: false,
        ...row.editTemp
        // 通过解构来拷贝
        // name: row.editTemp.name,
        // state: row.editTemp.state,
        // description: row.editTemp.description
      })
    },
    async delRole(id) {
      // 调用api
      await delRoleApi(id)

      // 判断当前页是否只有一条数据且大于1页
      if (this.roleData.length === 1 && this.params.page > 1) {
        this.params.page--
      }
      this.$message.success('删除成功~')
      await this.handleCurrentChange(this.params.page)
    },

    // 打开分配权限弹窗
    async btnPermission(id) {
      this.currentRoleId = id
      // 1. 获取所有的权限
      this.permissionData = transListToTreeData(await getPermissionListApi(), 0)
      // 2. 获取角色拥有的权限
      const { permIds } = await getRoleDetailApi(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      // console.log(this.$refs.perTreeRef.getCheckedKeys())
      await assignPermApi({
        id: this.currentRoleId,
        permIds: this.$refs.perTreeRef.getCheckedKeys()
      })
      this.$message.success('权限分配成功')
      this.showPermissionDialog = false
      this.permIds = []
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
